package org.speed.jdk;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 背景：取模法
 * 一致性Hash算法
 * 原理：通过增加虚拟节点减少节点增减后hash大量迁移问题
 * 
 */
public class ConsistHash {
	
	static SortedMap<String,String> sortMap = new TreeMap<>();
	static String[] serverNodes = new String[] {"192.168.0.1","192.168.3.1","191.168.1.2"};
	static int counts = 10;

	static {
		
		for(int i = 0 ;i < counts ; i ++ ) {
			for (String server : serverNodes) {
				server = server + "#" + i;
				sortMap.put(mHash(server), server);
			}
		}
	}
	
	static String mHash(String obj) {
		
		final int p = 16777619;
	    int hash = (int)2166136261L;
	    for (int i = 0; i < obj.length(); i++) {
	    	hash = (hash ^ obj.charAt(i)) * p;
	    }
	    
	    hash += hash << 13;
	    hash ^= hash >> 7;
	    hash += hash << 3;
	    hash ^= hash >> 17;
	    hash += hash << 5;
	 
	    if (hash < 0) {
	    	hash = Math.abs(hash);
	    }
	    
	    return String.valueOf(hash);
	}
	
	static void locationServer(String client) {
		String key = sortMap.tailMap(mHash(client)).firstKey();
		String server = sortMap.get(key);
		
		System.out.println("client=" + client + ",server=" + server);
	}
	
	public static void main(String[] args) {
		
		String[] clientServers = {"10.2.1.1","110.21.1.1","210.12.112.1","10.2.12.1"};
		for (String client : clientServers) {
			locationServer(client);
		}
		
	}
}
